package com.atguigu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/5/20 13:50
 */
public class Dwd_02_DwdTrafficUvDetailApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dwd_02_DwdTrafficUvDetailApp().init(3002,
                                                2,
                                                "Dwd_02_DwdTrafficUvDetailApp",
                                                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<String> firstWindowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstWindowState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("firstWindowState", String.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    String yesterday = firstWindowState.value();
                    String today = AtguiguUtil.toDate(ctx.window().getStart());
                    
                    if (!today.equals(yesterday)) {
                        // 当天的第一个窗口
                        firstWindowState.update(today);
                        
                        // 把窗口内所有的元素放入到list, 找出时间戳最小
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        
                        // Collections.min(list, (o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")))
                        JSONObject min = Collections.min(list, Comparator.comparing(o -> o.getLong("ts")));
                        out.collect(min);
                    }
                }
            })
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_UV_DETAIL));
    }
}
/*

UV: 独立访客数

过滤出来每个用户的当天的第一条访问记录

------------

数据源:
    启动日志
      计算uv, 记录数会偏小
      
      浏览器访问
          没有启动日志
      
      app客户端
           才有启动日志
           
    页面日志
        选择这个

第一条page日志的记录
    用一个状态记录最后一次访问记录日期
        如果来一条数据, 和状态同一天, 则忽略
        
        如果不会同一条, 则保留, 并且更新状态
        
     
     解决数据乱序问题:
        事件时间+窗口
        
        使用状态找当天的第一个窗口
            第一个窗口内时间戳最小的那条记录
            
         其他窗口数据, 全部忽略
         
    
        




*/